<template>
  <div class="container-fluid py-4">
    <div class="row">
      <div class="col-12">
        <div class="card shadow-sm border-0 rounded-3">
          <div class="card-header bg-primary text-white rounded-top-3">
            <h4 class="card-title mb-0">
              <i class="bi bi-card-list me-2"></i>我的发布
            </h4>
          </div>
          
          <div class="card-body">
            <!-- 表单形式 -->
            <div class="posts-list">
              <div v-for="post in userPosts" :key="post.id" class="post-item mb-4">
                <div class="card post-card border rounded-3 shadow-sm h-100">
                  <div class="card-body post-content d-flex flex-column flex-md-row gap-3">
                    <!-- 添加封面图片区域 -->
                    <div class="post-image-section rounded-2 overflow-hidden" style="flex: 0 0 150px;">
                      <img 
                        v-if="post.coverImage" 
                        :src="post.coverImage" 
                        :alt="post.title" 
                        class="post-cover-image img-fluid w-100 h-100 object-fit-cover"
                      >
                      <div v-else class="no-image d-flex align-items-center justify-content-center bg-light h-100">
                        <i class="bi bi-image text-muted" style="font-size: 2rem;"></i>
                      </div>
                    </div>
                    
                    <div class="flex-grow-1">
                      <div class="post-main-section">
                        <div class="post-header d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
                          <h5 class="post-title mb-0 text-truncate">{{ post.title }}</h5>
                          <div class="post-tags d-flex gap-2">
                            <span class="badge bg-primary">{{ post.categories }}</span>
                            <span class="badge" :class="getUrgentTagClass(post.isUrgent)">
                              {{ formatUrgentStatus(post.isUrgent) }}
                            </span>
                            <span class="badge" :class="getStatusTagClass(post.status)">
                              {{ formatStatus(post.status) }}
                            </span>
                          </div>
                        </div>
                        
                        <div class="post-meta d-flex flex-wrap gap-3 mb-3">
                          <div class="meta-item d-flex align-items-center">
                            <i class="bi bi-geo-alt text-muted me-1"></i>
                            <span class="meta-label text-muted small me-1">地点:</span>
                            <span class="meta-value">{{ post.location || '未指定' }}</span>
                          </div>
                          <div class="meta-item d-flex align-items-center price-item">
                            <i class="bi bi-currency-dollar text-muted me-1"></i>
                            <span class="meta-label text-muted small me-1">价格:</span>
                            <span v-if="post.price" class="meta-value fw-bold text-success">{{ post.price }}元</span>
                            <span v-else class="meta-value text-muted">无价格</span>
                          </div>
                          <div class="meta-item d-flex align-items-center">
                            <i class="bi bi-eye text-muted me-1"></i>
                            <span class="meta-label text-muted small me-1">浏览量:</span>
                            <span class="meta-value">{{ post.viewCount }}</span>
                          </div>
                        </div>
                      </div>
                      
                      <div class="post-footer d-flex flex-wrap justify-content-between align-items-center pt-3 border-top">
                        <div class="post-time d-flex align-items-center text-muted small">
                          <i class="bi bi-clock me-1"></i>
                          <span class="meta-label me-1">发布时间:</span>
                          <span class="meta-value">{{ post.createdAt }}</span>
                        </div>
                        <div class="post-actions d-flex gap-2">
                          <button class="btn btn-outline-primary btn-sm rounded-pill px-3" @click="editPost(post)">
                            <i class="bi bi-pencil-square me-1"></i>编辑
                          </button>
                          <button class="btn btn-outline-danger btn-sm rounded-pill px-3" @click="deletePost(post)">
                            <i class="bi bi-trash me-1"></i>删除
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 添加分页组件 -->
            <div class="pagination-container d-flex justify-content-center mt-4">
              <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="totalPosts"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getPostListService,
         getCategoriesListService,
         deletePostService,
         getPostCoverService,
        } from '@/api/post.js'
const router = useRouter()


const userPosts = ref([])// 用户帖子列表
// 分页相关数据
const pageNum = ref(1)
const pageSize = ref(5) // 默认每页5条
const totalPosts = ref(0) // 添加总数量
// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1
  fetchUserPosts() // 重新获取数据
}

// 当前页改变
const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchUserPosts() // 重新获取数据
}

// 获取用户发布的帖子
const fetchUserPosts = async () => {
  const categoriesRes = await getCategoriesListService()// 获取分类列表
  
  let coverImagesRes = null;
  
  try {
    coverImagesRes = await getPostCoverService()// 获取帖子图片
    console.log(coverImagesRes.data)
  } catch (error) {
    console.error('获取封面图片失败:', error)
  }
  
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }

  try {
    const res = await getPostListService(params)
    userPosts.value = res.data.items  // 将数据赋值给userPosts
    totalPosts.value = res.data.total
    
    // 为每个帖子添加分类名称
    userPosts.value.forEach(post => {
      const category = categoriesRes.data.find(cat => cat.id === post.categoryId)
      if (category) {
        post.categories = category.name
      }
    })
    
    // 为每个帖子添加第一张图片
    if (coverImagesRes && coverImagesRes.data) {
      userPosts.value.forEach(post => {
        // 查找该帖子的所有图片并只取第一张
        const postImages = coverImagesRes.data.filter(img => img.postId === post.id);
        if (postImages.length > 0) {
          const firstImage = postImages[0];
          // 添加前缀到图片URL
          post.coverImage = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
      })
    }
  } catch (error) {
    console.error('获取发布信息失败:', error)
    if (error.response && error.response.data) {
      console.error('服务器返回错误:', error.response.data)
      ElMessage.error(error.response.data.message || '获取发布信息失败')
    } else {
      ElMessage.error('获取发布信息失败，请稍后重试')
    }
  }
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    sold: '已售出'
  }
  return statusMap[status] || status
}

// 获取状态标签类型 (用于Element Plus tag)
// const getStatusTagType = (status) => {
//   const typeMap = {
//     pending: 'warning',
//     approved: 'success',
//     rejected: 'danger',
//     sold: 'info'
//   }
//   return typeMap[status] || 'info'
// }

// 获取状态标签CSS类 (用于Bootstrap badge)
const getStatusTagClass = (status) => {
  const classMap = {
    pending: 'bg-warning text-dark',
    approved: 'bg-success',
    rejected: 'bg-danger',
    sold: 'bg-info text-dark'
  }
  return classMap[status] || 'bg-info text-dark'
}

// 格式化紧急状态显示
const formatUrgentStatus = (isUrgent) => {
  return isUrgent ? '紧急' : '普通'
}

// 获取紧急状态标签类型 (用于Element Plus tag)
const getUrgentTagType = (isUrgent) => {
  return isUrgent ? 'danger' : 'success'
}

// 获取紧急状态标签CSS类 (用于Bootstrap badge)
const getUrgentTagClass = (isUrgent) => {
  return isUrgent ? 'bg-danger' : 'bg-success'
}

// 编辑帖子
const editPost = (row) => {
  router.push(`/user/posts/edit/${row.id}`)
}

// 删除帖子
const deletePost = (row) => {
  ElMessageBox.confirm('确定要删除这篇帖子吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePostService(row.id)
      ElMessage.success('删除成功')
      fetchUserPosts()
    } catch  {
      ElMessage.error('删除失败')
    }
  })
}

onMounted(() => {
  fetchUserPosts()// 初始化用户帖子列表
})
</script>

<style scoped>
.card {
  transition: all 0.3s ease;
}

.card:hover {
  transform: translateY(-3px);
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

.post-cover-image {
  height: 120px;
  object-fit: cover;
}

.badge {
  font-size: 0.75em;
}

.price {
  color: #198754;
  font-weight: 500;
}

.pagination-container :deep(.el-pagination) {
  padding: 0;
}

.pagination-container :deep(.el-pagination .el-pager li.active) {
  background-color: #0d6efd;
}

.pagination-container :deep(.el-pagination button:hover) {
  color: #0d6efd;
}

.pagination-container :deep(.el-pagination .el-pager li:hover) {
  color: #0d6efd;
}

.object-fit-cover {
  object-fit: cover;
}

.text-truncate {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>